import { sm2 } from 'sm-crypto';

// 不同判断条件 映射 元组
export function mapDoSecret(config) {
  const map = [
    [
      () => config.params && typeof config.params === 'object',
      () => {
        config.url = config.url + "?" + doSecret(formatObjToAddress(config.params))
        delete config.params
      }
    ],
    [
      () => config.data && typeof config.data === 'object',
      () => {
        config.data = doSecret(JSON.stringify(config.data))
      }
    ]
  ]
  const target = map.find(item => item[0]())
  // 满足条件
  if (target) {
    target[1]()
    return config
  } else { //所有条件不满足
    return config
  }
}

/** 递归加密 **/
export function doSecret(paramObject) {
  if (!paramObject) {
    return paramObject;
  }
  let result = "";
  if (typeof paramObject == 'object') {
    for (let k in paramObject) {
      paramObject[k] = doSecret(paramObject[k])
    }
  } else {
    result = doStringSecrete(paramObject);
  }
  return result;
}

export function doStringSecrete(str) {
  return rsaPublicData(str);
}


function rsaPublicData(data) {
  //publicKey 为sm2的公钥，公钥用来加密，私钥用来解密
  //示例对应的私钥为 74a89d4e78dd999a1882e0202566ee8971464eaf097dede170c86ad683e6e751  用来给后端解密用
  const publicKey =
    '04baddc88403b9a137267082f970e715e8abcb80fa3eda8a3e50c80c9ccf04b34a19dc94cc0f2db8e2ed8cb6e66a0f38dbc80d77ef9b64653ae439a45d309d9f67';

  const cipherMode = 1;
  //data为加密的数据
  const result = sm2.doEncrypt(data, publicKey, cipherMode);
  return result;
}
